package P4树形结构;

import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;
import java.util.PriorityQueue;
public class LC347 {
    class Freq {
        int num;
        int count;
        public Freq(int num, int count) {
            this.num = num;
            this.count = count;
        }
    }

    public int[] topKFrequent(int[] nums, int k) {
        HashMap<Integer, Integer> map = new HashMap<>();
        for (int num : nums) {
            map.put(num, map.getOrDefault(num, 0) + 1);
        }
        PriorityQueue<Freq> queue = new PriorityQueue<Freq>(new Comparator<Freq>() {
            @Override
            public int compare(Freq o1, Freq o2) {
                return o2.count - o1.count;
            }
        });
        for (Map.Entry<Integer,Integer> entry : map.entrySet()) {
            queue.add(new Freq(entry.getKey(),entry.getValue()));
        }
        int[] arr = new int[k];
        for (int i = 0;i < arr.length; i++) {
            arr[i] = queue.poll().num;
        }
        return arr;
    }
}